package com.qf.filter;

import com.qf.user.entity.User;
import com.qf.utils.JWTUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

/**
 * 作者：熊剑
 * 时间：2023/10/16
 * 描述：
 */
public class TokenFilter extends BasicAuthenticationFilter {
    public TokenFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        //获取令牌
        String token = request.getHeader("token");

        //将token放入SecurityContext中
        try {
            //priciple
            User user = JWTUtil.parseToken(token);
            //用户权限列表
            Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
            //将用户信息存放到securityContext中
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user,null,authorities);
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        } catch (Exception e) {

        }

        //放行
        chain.doFilter(request,response);
    }
}
